<?php

    class ProfesorController extends AppController {

        var $name = "Profesor";

        var $uses = array( "User", "Theme", "Stage", "Task", "Commit" );

        public function beforeFilter() {

            parent::beforeFilter();

        }


        /**
         *
         */
        public function index() {
            $this->redirect( array( "action" => "afisare_teme" ) );
        }

        /**
         * @param null $id reprezinta id-ul utilizatorului logat
         */
        public function profile( $id = null ) {
            $themes = $this->Theme->find('all',array('conditions'=>array('id_stud !='=>0, 'id_user'=>$this->Auth->user('id'))));
                $students = array();
                foreach($themes as $theme)
                    $students[] = $theme['Stud'];
                $commits = array();
                foreach($students as $s)
                    {
                    self::get_commit( $s['id'] );
                    }
            
            $this->User->id = $this->Auth->user( "id" );
            if( $this->data == null ) {
                $this->data = $this->User->read();
            }
            if( $this->request->is( "post" ) ) {
                if( $this->request->data["User"]['password'] == "" ) {
                    $this->User->validator()
                               ->remove( "password" );
                    $do_not_update[] = "password";
                }
                if( $this->User->save( $this->request->data, true, array_diff( array_keys( $this->User->schema() ), $do_not_update ) ) ) {
                    $this->Session->setFlash( "Updated", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Could not update! Please review your input and try again", "flash_error" );
                }
            }
        }

        /**
         * este apelata atunci cand se aauga o noua tema, adauga tema in baza de date
         */
        public function adaugare_tema() {
            if( $this->data == null ) {
                $this->data = $this->Theme->read();
            }

            if( ! isset( $this->request->data['Theme']['id_user'] ) ) {
                $this->request->data['Theme']['id_user'] = $this->Auth->user( "id" );
            }
            if( $this->request->is( "post" ) ) {
                $ok = 1;
                for( $i = 0; $i < 40; $i ++ ) {
                    if( isset( $this->data['Requirement' . $i] ) ) {
                        $data = $this->data['Requirement' . $i];
                        $type = $data['type'];
                        if( $type != 'text' ) {
                            if( $data['type_values'] == '' ) {
                                $ok = 0;
                                break;
                            }
                        }
                        if( $data['name'] == '' ) {
                            $ok = 0;
                            break;
                        }
                        if( $data['description'] == '' ) {
                            $ok = 0;
                            break;
                        }
                    }
                    else {
                        break;
                    }
                }
                if( $ok && $this->Theme->save( $this->request->data ) ) {
                    $id = $this->Theme->getLastInsertID();
                    for( $i = 0; $i < 40; $i ++ ) {
                        if( isset( $this->data['Requirement' . $i] ) ) {
                            $data = $this->data['Requirement' . $i];
                            $this->Requirement->create( array(
                                                            'id_theme'    => $id,
                                                            'type'        => $data['type'],
                                                            'type_values' => $data['type_values'],
                                                            'required'    => ( isset( $data['required'] ) ? 1 : 0 ),
                                                            'name'        => $data['name'],
                                                            'description' => $data['description'],
                                                        ) );
                            $this->Requirement->save();
                        }
                        else {
                            break;
                        }
                    }
                    $this->Session->setFlash( "Tema salvata", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Nu s-a putut salva tema,icercati din nou", "flash_error" );
                }
            }

        }

        /**
         * @param null $id_tema Id-ul temei
         *                      preia datele de pe formular si updateaza tema cu id-ul primit ca parametru

         */
        public function editare_tema( $id_tema = null ) {

            $theme = $this->Theme->find( 'first', array( 'conditions' => array( 'Theme.id' => $id_tema ) ) );
            $reqs  = $this->Requirement->find( 'all', array( 'conditions' => array( 'Requirement.id_theme' => $id_tema ) ) );


            if( ! isset( $this->request->data['Theme']['id_user'] ) ) {
                $this->request->data['Theme']['id_user'] = $this->Auth->user( "id" );
            }
            if( $this->request->is( "post" ) ) {
                $ok = 1;
                for( $i = 0; $i < 40; $i ++ ) {
                    if( isset( $this->data['Requirement' . $i] ) ) {
                        $data = $this->data['Requirement' . $i];
                        $type = $data['type'];
                        if( $type != 'text' ) {
                            if( $data['type_values'] == '' ) {
                                $ok = 0;
                                break;
                            }
                        }
                        if( $data['name'] == '' ) {
                            $ok = 0;
                            break;
                        }
                        if( $data['description'] == '' ) {
                            $ok = 0;
                            break;
                        }
                    }
                    else {
                        break;
                    }
                }
                $this->Theme->set( array( 'id' => $id_tema ) );
                if( $ok && $this->Theme->save( $this->request->data ) ) {
                    $id = $id_tema;
                    for( $i = count( $reqs ); $i < 40; $i ++ ) {
                        if( isset( $this->data['Requirement' . $i] ) ) {
                            $data = $this->data['Requirement' . $i];
                            $this->Requirement->create( array(
                                                            'id_theme'    => $id,
                                                            'type'        => $data['type'],
                                                            'type_values' => $data['type_values'],
                                                            'required'    => ( isset( $data['required'] ) ? 1 : 0 ),
                                                            'name'        => $data['name'],
                                                            'description' => $data['description'],
                                                        ) );
                            $this->Requirement->save();
                        }
                        else {
                            break;
                        }
                    }
                    $this->Session->setFlash( "Tema salvata", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Nu s-a putut salva tema,icercati din nou", "flash_error" );
                }
            }
            $theme = $this->Theme->find( 'first', array( 'conditions' => array( 'Theme.id' => $id_tema ) ) );
            $reqs  = $this->Requirement->find( 'all', array( 'conditions' => array( 'Requirement.id_theme' => $id_tema ) ) );
            $this->set( 'theme', $theme );
            $this->set( 'reqs', $reqs );
        }

        /**
         * Afiseaza temele disponibile ale unui profesor
         *
         */
        public function afisare_teme() {
            $this->Paginator->settings['paramType']  = 'querystring';
            $this->Paginator->settings['limit']      = '25';
            $conditions                              = array('Theme.id_user'=>$this->Auth->user('id'));
            $this->Paginator->settings['conditions'] = $conditions;
            $this->Paginator->settings['contain']    = array( "Stud" );
            $this->Paginator->settings['fields']     = array(
                "Theme.name",
                "Theme.id_stud",
                "Theme.modified",
                "Theme.id",
                "Stud.nume",
                "Stud.prenume"
            );
            $this->set( "teme", $this->Paginator->paginate( "Theme" ) );
            //  self::send_email(array("popica93@yahoo.com"=>"Popa Andrei"),"test",array("var1"=>"o variabila"));
        }

        /**
         * @param $id_tema
         * Se adauga o noua etapa la tema care are id-ul primit ca parametru
         */
        public function adaugare_etapa( $id_tema ) {
            if( $this->request->is( "post" ) ) {
                $date = $this->data['Stage']['limit_date'];
                if( strtotime( $date ) > time() + 60 * 60 && $this->Stage->validates( $this->data['Stage'] ) ) {
                    $this->Stage->create( $this->data['Stage'] );
                    $this->Stage->set( array(
                                           'limit_date' => date( 'Y-m-d H:i:s', strtotime( $date ) ),
                                           'id_theme'   => $id_tema
                                       ) );
                    $this->Stage->save();
                    $id = $this->Stage->getLastInsertID();
                    for( $i = 0; $i < 40; $i ++ ) {
                        if( isset( $this->data['Task' . $i] ) ) {
                            $data = $this->data['Task' . $i];
                            $this->Task->create( array(
                                                     'id_stage' => $id,
                                                     'name'     => $data['name'],
                                                 ) );
                            $this->Task->save();
                        }
                        else {
                            break;
                        }
                    }
                    $this->Session->setFlash( "Success", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Could not update! Please review your input and try again", "flash_error" );
                }
            }
        }

        /**
         * @param null $id_etapa
         * Aduge modificari la etapa cu if-ul primit ca parametru
         */
        public function editare_etapa( $id_etapa = null ) {
            $stage = $this->Stage->find( 'first', array( 'conditions' => array( 'Stage.id' => $id_etapa ) ) );
            $tasks = $this->Task->find( 'all', array( 'conditions' => array( 'Task.id_stage' => $id_etapa ) ) );


            if( $this->request->is( "post" ) ) {
                $ok   = 1;
                $date = $this->data['Stage']['limit_date'];
                $this->Stage->set( array(
                                       'id'          => $id_etapa,
                                       'limit_date'  => date( 'Y-m-d H:i:s', strtotime( $date ) ),
                                       'name'        => $this->data['Stage']['name'],
                                       'description' => $this->data['Stage']['description']
                                   ) );
                if( strtotime( $date ) > time() + 60 * 60 && $this->Stage->validates( $this->data['Stage'] ) ) {
                    $this->Stage->save();
                    $id = $id_etapa;
                    for( $i = count( $tasks ); $i < 40; $i ++ ) {
                        if( isset( $this->data['Task' . $i] ) ) {
                            $data = $this->data['Task' . $i];
                            $this->Task->create( array(
                                                     'name'     => $data['name'],
                                                     'id_stage' => $id
                                                 ) );
                            $this->Task->save();
                        }
                        else {
                            break;
                        }
                    }
                    $this->Session->setFlash( "Tema salvata", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Nu s-a putut salva tema, incercati din nou", "flash_error" );
                }
            }
            $stage = $this->Stage->find( 'first', array( 'conditions' => array( 'Stage.id' => $id_etapa ) ) );
            $tasks = $this->Task->find( 'all', array( 'conditions' => array( 'Task.id_stage' => $id_etapa ) ) );
            $this->set( 'stage', $stage );
            $this->set( 'tasks', $tasks );
        }

        /**
         *
         */
        public function stergere_tema() {
            if( $this->data == null ) {
                $this->data = $this->Theme->read();
            }
            if( ! isset( $this->request->data['Theme']['id_user'] ) ) {
                $this->request->data['Theme']['id_user'] = $this->Auth->user( "id" );
            }
            if( $this->Theme->delete( $this->request->query ) ) {
                $this->Session->setFlash( "Tema stearsa!", "flash_success" );
            }
            else {
                $this->Session->setFlash( "Nu s-a putut sterge tema,incercati din nou", "flash_error" );
            }

            $this->redirect( $this->referer() );
        }

        /**
         * @param int $id
         */
        public function stergere_etapa( $id = null ) {
            if( $this->Stage->delete( $id ) ) {
                $this->Session->setFlash( "Etapa stearsa!", "flash_success" );
            }
            else {
                $this->Session->setFlash( "Nu s-a putut sterge etapa,incercati din nou", "flash_error" );
            }
            $this->redirect( $this->referer() );
        }

        /**
         * @param null $id
         * Extrage datele pentru tema cu id-ul primit ca parametru si apoi trimite datele spre view
         */
        public function vizualizare_tema( $id = null ) {
            $this->set( "tema", $this->Theme->find( "first", array(
                "conditions" => array( "Theme.id" => $id ),
                "contain"    => array( "Stud", "Stage", "Stage.Task", 'Extra' ),
                "recursive"  => 2
            ) ) );
            
        }

        public function verificare_deadline() {
            $teme = $this->Theme->find( "all", array( "contain" => array( "User", "Stud", "Stage" ) ) );
            $now  = time();
            foreach( $teme as $tema ) {
                if( $tema['Theme']['id_stud'] != 0 ) {
                    foreach( $tema['Stage'] as $stage ) {
                        if( strtotime( $stage['limit_date'] ) > $now && $stage['done'] == 0 ) {
                            $body = array( "var1" => "Data limita pentru " . $stage['name'] . "a fost depasita!" );
                            $this->send_email_to_profesor( $tema['User']['id'], "profesor_deadline", $body );
                            $this->send_email_to_student( $tema['Stud']['id'], "student_deadline", $body );
                        }
                    }
                }
            }
        }

        /**
         * @param null $id_user *
         *                      se verifica daca studentul cu id-ul primit ca parametru a realizat un nou commit, in caz afirmativ se tremite mail catre profesor
         */
        public function get_commit( $id_user = null ) {
            require_once( '../webroot/Github/client/GitHubClient.php' );
            $stud         = $this->User->find( 'first', array( 'conditions' => array( 'User.id' => $id_user ) ) );
            $prof         = $this->User->find( 'first', array( 'conditions' => array( 'User.id' => $id_user ) ) );
            $stud_commits = $this->Commit->find( 'all', array( 'conditions' => array( 'Commit.id_student' => 2 ) ) );

            $owner = $stud['User']['git_owner'];
            $repo = $stud['User']['git_repo'];
            //$owner = 'tan-tan-kanarek';
            //$repo  = 'github-php-client';

            $client = new GitHubClient();
            $client->setPage();
            $client->setPageSize( 2 );
            $commits = $client->repos->commits->listCommitsOnRepository( $owner, $repo );
            foreach( $commits as $commit ) {
                $ok = 0;
                foreach( $stud_commits as $stud_commit ) {
                    if( $commit->getSha() == $stud_commit['Commit']['sha'] ) {
                        $ok = 1;
                    }
                }
                if( $ok == 0 ) {
                    $body = array( "var1" => "Studentul ".$stud['User']['nume']." ".$stud['User']['prenume']." a realizat un nou commit <br>". $commit->getUrl(),"prof"=>$this->Auth->user("nume") );
                    self::send_email_to_profesor( $this->Auth->user( "id" ), "test", $body );
                    $this->Commit->save( array(
                                             'id_student'  => $id_user,
                                             'id_profesor' => $this->Auth->user( "id" ),
                                             'git_repo'    => $stud['User']['git_repo'],
                                             'git_owner'   => $stud['User']['git_owner'],
                                             'email_sent'  => 1,
                                             'sha'         => $commit->getSha(),
                                             'url'         => $commit->getUrl(),
                                         ) );

                }
            }

            $commits = $client->getNextPage();

            foreach( $commits as $commit ) {
                $ok = 0;
                foreach( $stud_commits as $stud_commit ) {
                    if( $commit->getSha() == $stud_commit['Commit']['sha'] ) {
                        $ok = 1;

                    }
                }
                if( $ok == 0 ) {
                    $body = array( "var1" => "Studentul".$stud['User']['nume']." ".$stud['User']['prenume']."a realizat un nou commit.<br>". $commit->getUrl(),"prof"=>$this->Auth->user("nume") );
                    self::send_email_to_profesor( $this->Auth->user( "id" ), "test", $body );
                    $this->Commit->save( array(
                                             'id_student'  => $id_user,
                                             'id_profesor' => $this->Auth->user( "id" ),
                                             'git_repo'    => $stud['User']['git_repo'],
                                             'git_owner'   => $stud['User']['git_owner'],
                                             'email_sent'  => 1,
                                             'sha'         => $commit->getSha()
                                         ) );
                }
            }
        }
        /***
         * verifica daca sunt modificari
         */
        public function see_issues() {
            $themes = $this->Theme->find('all',array('conditions'=>array('id_stud !='=>0, 'id_user'=>$this->Auth->user('id'))));
            $students = array();
            foreach($themes as $theme)
                $students[] = $theme['Stud'];
            $commits = array();
            foreach($students as $s)
                {
                $comms = $this->Commit->find('all',array('conditions'=>array('id_student'=>$s['id'],'checked'=>'0')));
                foreach($comms as $comm)
                    $commits[] = $comm;
                }
            foreach($commits as $comm)
                {
                $this->Commit->set(array('checked'=>1,
                'id'=>$comm['Commit']['id']
                ));
                }
            $this->set('commits',$commits);
            $Ss = array();
            $themes = $this->Theme->find('all',array('recursive'=>-1,'conditions'=>array('id_stud !='=>0, 'id_user'=>$this->Auth->user('id'))));
            if ($themes)
                {
                for($i=0; $i<count($themes); $i++)
                    {
                    $theme = $themes[$i];
                    $stages = $this->Stage->find('all',array('recursive'=>-1,'conditions'=>array(
                        'id_theme'=>$theme['Theme']['id'],
                        'limit_date <'=>date('Y-m-d H:i:s')
                        )));
                        
                        
                    if ($stages)
                        $themes[$i]['Stages'] = $stages;
                    }
                }


            $this->set( 'themes', $themes );
        }

        /**
         * @param $id_tema
         * adauga fisiere pentru tema cu id-ul dat ca parametru
         */

        public function add_extra( $id_tema ) {
            if( $this->request->is( "post" ) ) {
                $do_not_update = array();
                $this->Extra->create( $this->request->data );
                $this->Extra->set( array(
                                       'path' => '',
                                   ) );

                $teme = $this->Stages->find( 'all', array( 'conditions' => array( 'Theme.id' => $id_tema ) ) );
                $this->set( 'temele', $teme );

                $target_path = "./uploads/";
                $target_path = $target_path . basename( $this->data["Extra"]['path']['name'] );
                if( move_uploaded_file( $this->data["Extra"]['path']['tmp_name'], $target_path ) ) {
                    $this->Extra->set( array(
                                           'path' => $target_path,
                                       ) );
                }
                else {
                    echo "There was an error uploading the file, please try again!";
                }

                if( $this->Extra->save() ) {
                    $this->Session->setFlash( "Updated", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Could not update! Please review your input and try again", "flash_error" );
                }
            }
        }

    }